package cycling.taxi.com.ui.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import cycling.taxi.com.IConstants;
import cycling.taxi.com.R;
import cycling.taxi.com.person.ExitApplication;
import cycling.taxi.com.request.Config;
import cycling.taxi.com.request.RM;
import cycling.taxi.com.request.RequestBean;
import cycling.taxi.com.request.RequestCallback;
import cycling.taxi.com.request.RequestParams;
import cycling.taxi.com.request.RequestUtil;
import cycling.taxi.com.utils.LogUtil;
import cycling.taxi.com.utils.MD5Util;
import cycling.taxi.com.utils.PhoneUtils;
import cycling.taxi.com.utils.SPUtil;
import cycling.taxi.com.utils.ToastUtil;
import cycling.taxi.com.utils.Urls;

import static cycling.taxi.com.R.id.validate;

public class StealActivity extends AppCompatActivity implements View.OnClickListener,RequestCallback {

    private ImageView back;
    private EditText stealname;
    private EditText stealmobile;
    private EditText stealval;
    private Button repair_btn;
    private RequestQueue queue;
    private String content;
    private String beanJson;
    private String status;
    private Button validate;
    private TextView mTitleText;
    private String rad="()*";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_steal);
        ExitApplication.getInstance().addActivity(this);
        back=(ImageView)findViewById(R.id.back);
        stealname=(EditText)findViewById(R.id.stealname);
        stealmobile=(EditText)findViewById(R.id.stealmobile);
        stealval=(EditText)findViewById(R.id.stealval);
        repair_btn=(Button)findViewById(R.id.repair_btn);
        mTitleText=(TextView)findViewById(R.id.title_text);
        validate=(Button)findViewById(R.id.validate);
        back.setOnClickListener(this);
        repair_btn.setOnClickListener(this);
        queue= Volley.newRequestQueue(this);
        validate.setOnClickListener(this);
        mTitleText.setText("失窃上报");

    }


    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.repair_btn){
            Send();
            finish();
        }
        if (v.getId() ==R.id.back){
            finish();
        }
        if(v.getId()==R.id.validate){

        reqIdentifyCode();
        }

    }
    private void Send() {
        if (TextUtils.isEmpty(getName())){
            ToastUtil.getInstance().toast("联系人");
            return;

        }
        if (TextUtils.isEmpty(getPhone())){
            ToastUtil.getInstance().toast("请输入手机号");
            return;

        }
        if (!PhoneUtils.isMobileNO(getPhone())) {
            ToastUtil.getInstance().toast("手机号码不正确");
            return;
        }
        if (TextUtils.isEmpty(getverifyCode())||getverifyCode().length()<4||!getverifyCode().equals(rad)){
            ToastUtil.getInstance().toast("验证码不正确");return;
        }
        //获取服务器数据
        RequestParams params = new RequestParams.Builder()
                .putParam("beanJson", SPUtil.getInstance().getData("beanJson"))
                .putParam("lianxiren",getName())
                .putParam("phone",getPhone())
                .putParam("verhicledata",SPUtil.getInstance().getData("verhicledata"))
                .build();

        //开始请求发送数据到服务器服务器
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String url =  Urls.getSteal();
        RequestUtil.requestData(requestQueue,
                IConstants.TRAJECTORY,
                url,
                RM.GET,
                RequestBean.class,
                params,
                this);
    }

    @Override
    public void requestSuccess(RequestBean bean, Config config) {
            if(bean.getStatusCode()==1){
                ToastUtil.getInstance().toast("提交成功");
            }
            if (bean.getStatusCode()==2)
            {
                ToastUtil.getInstance().toast("不要重复提交");
            }
            if (bean.getStatusCode()==3) {
                ToastUtil.getInstance().toast("不是注册手机号");
            }
    }

    @Override
    public void requestFail(RequestBean bean, Config config) {
        ToastUtil.getInstance().toast("提交失败");
    }

    @Override
    public void requestTokenInvalid(String requestTag, Config config) {

    }
    private String getName() {
        return stealname.getText().toString().trim();
    }
    private String getPhone() {
        return stealmobile.getText().toString().trim();
    }
    private String getval() {
        return stealval.getText().toString().trim();
    }
    private void reqIdentifyCode() {
        String phone = getPhone();
        if (!PhoneUtils.isMobileNO(phone)) {
            ToastUtil.getInstance().toast("手机号码不正确");
            return;
        }
        rad = RandomCode();
        volleyGet();
//        String noncestr = "" + System.currentTimeMillis(); //时间戳
//        String sign = IdentifyUtils.getClientSign(phone, noncestr); //签名
        //TODO  下面需要进行网络请求

        //请求成功的话加上以下代码
        startColdTime();

    }
    public void volleyGet(){
      //  String path= "http://172.16.2.183:8080/CyclingBgTV1/appRepairByself/r.dop?content="+rad;
      //  String path= Urls.getTest()+"?content="+rad;
        String mobile=getPhone();
        String path =Urls.getValidate()+mobile+Urls.getValidateContent()+rad+Urls.getValidateElse();
        //String path="https://dx.ipyy.net/smsJson.aspx?action=send&userid=&account=AG00031&password=AG00031523&mobile="+mobile+"&content=您的验证码："+rad+"【塔西】&sendTime=&extno=";
        // String path = Urls.getRepair();18677365372
        StringRequest request = new StringRequest(path, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                LogUtil.e(s);
                ToastUtil.getInstance().toast(s);
            }
        },null);
        queue.add(request);
    }
    private int timeC = 0;
    private void startColdTime() {
        timeC = 60;
        coldTimeing();
    }

    private void coldTimeing() {
        if (validate == null)
            return;
        setColdTime(timeC);
        if (timeC > 0) {
            validate.postDelayed(new Runnable() {
                @Override
                public void run() {
                    timeC--;
                    coldTimeing();
                }
            }, 1000);
        }
    }

    /**
     * @param num 倒计时时间, 如果小于等于0, 显示重新发送
     */
    private void setColdTime(int num) {
        if (validate == null) {
            return;
        }
        validate.setEnabled(num <= 0);
        if (num > 0) {
            validate.setText(num + "s");
        } else {
            validate.setText(R.string.str_register_resend);
        }
    }
    private String RandomCode(){
        String str="0123456789";
        StringBuilder sb=new StringBuilder(4);
        for(int i=0;i<4;i++)
        {
            char ch=str.charAt(new Random().nextInt(str.length()));
            sb.append(ch);
        }
        return sb.toString();
    }
    private String getverifyCode() {
        return stealval.getText().toString().trim();
    }
}
